package userService

import (
	"chart.zozoo.net/app/dao/usersDao"
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"strconv"
	"time"
)

// Info 根据id获取用户信息
func Info(id int, params ...string) (u *models.Users, err error) {
	u = &models.Users{}
	redisKey := "user:id:" + strconv.Itoa(id) + ":json"
	if len(params) == 0 {
		params = append(params, "get")
	}

	switch params[0] {
	case "update":
		break
	case "delete":
		myRedis.RedisClient.Del(redisKey)
		return nil, nil
	default:
		res := myRedis.RedisClient.Get(redisKey)
		if res.Err() == nil {
			val := res.Val()
			err = json.Unmarshal([]byte(val), u)
			if err != nil {
				return nil, err
			}

			return u, nil
		}
	}

	//缓存不存在，查询数据库
	u, err = usersDao.Info(id)
	if err != nil {
		return nil, err
	}

	//保存缓存
	uStr, err := json.Marshal(u)
	if err != nil {
		return nil, err
	}
	myRedis.RedisClient.Set(redisKey, string(uStr), time.Hour*24)
	return u, nil
}
